import countries_data from "./data.js";
import countries from "i18n-iso-countries";
import zh from "i18n-iso-countries/langs/zh.json";
countries.registerLocale(zh);

export default function useCountries() {
  const getAlpha2Countries = () => {
    return countries_data.map((item) => {
      const { code2, cn_name, phone_code } = item;
      return {
        name: `${cn_name} / ${code2} / +${phone_code}`,
        code: code2,
        phone_code: phone_code,
      };
    });
  };
  const removeDigits = (str) => {
    return str.replace(/\d+/g, "");
  };

  const getAlpha3Countries = () => {
    return countries_data.map((item) => {
      const { code2, code3, cn_name, phone_code } = item;
      return {
        name: `${cn_name} / ${code3} / +${phone_code}`,
        code: code3,
        code2,
        phone_code: phone_code,
      };
    });
  };

  const getCountryName = (countryCode) => {
    if (!countryCode) return countryCode;
    const code = countryCode.toUpperCase();
    const name = countries.getName(code, "zh");
    return name || code;
  };

  const getCountryCode = (name) => {
    return countries.getAlpha2Code(name, "zh");
  };

  const removeDigitsAndSpaces = (str) => {
    return str.replace(/[\d\s]/g, ""); // \d 匹配数字，\s 匹配空格
  };
  const getCountriesListIcon = (name) => {
    return countries.alpha3ToAlpha2(removeDigits(name), "zh");
  };

  const getContryIcon = (name) => {
    const newName = removeDigitsAndSpaces(name.split("/")[1]);

    if (removeDigits(newName).length > 2) {
      console.log(getCountriesListIcon(newName)?.toLowerCase());
      return getCountriesListIcon(newName)?.toLowerCase();
    } else {
      return newName.toLowerCase();
    }
  };

  return {
    getCountryName,
    getCountryCode,
    countriesList: getAlpha2Countries(),
    countriesList3: getAlpha3Countries(),
    getCountriesListIcon,
    removeDigits,
    getContryIcon,
  };
}
